package com.heaven.exception.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.heaven.exception.BizCodeEnum;
import com.heaven.exception.RRException;
import com.heaven.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.multipart.MultipartException;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理用户接口异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.heaven.customerServer.customerController")
public class CustomerControllerAdvice {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class, WebExchangeBindException.class}) //指定扫描的异常
    public R handleValidException(Exception e){
        BindingResult bindingResult = null;
        if(e instanceof MethodArgumentNotValidException validException){
            bindingResult = validException.getBindingResult();
        }
        if(e instanceof WebExchangeBindException bindException){
            bindingResult = bindException.getBindingResult();
        }
        //log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        Map<String,String> res = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            // 获取异常字段的异常信息
            res.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION).put("data", res);
    }

    @ExceptionHandler(value = MultipartException.class)
    public R handleFileException(MultipartException e){
        log.error("upload file fail {}，type of exception:{}",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.MultipartException);
    }

    //处理所有的异常
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        log.error(e.getMessage(), e);
        return R.error();
    }

    @ExceptionHandler(NotLoginException.class)
    public R handleNotLoginException(NotLoginException e){
        return R.error(BizCodeEnum.USER_NOT_LOGIN.getCode(),BizCodeEnum.USER_NOT_LOGIN.getMsg()+"-"+e.getMessage());
    }

    @ExceptionHandler(value = RRException.class)
    public R handleOwnException(RRException throwable){
        //log.error("自定义异常{}，异常类型：{}",throwable.getMsg(),throwable.getClass());
        return R.error(throwable.getCode(), throwable.getMsg());
    }
}
